//基地址
axios.defaults.baseURL = 'https://hmajax.itheima.net'

//抽取轻提示函数
function show(msg = '') {
    const toastDom = document.querySelector('.my-toast')
    const toast = new bootstrap.Toast(toastDom)
    document.querySelector('.toast-body').innerHTML = msg
    toast.show()
}

//判断是否登录
function checkLogin() {
    //获取token
    const token = localStorage.getItem('hmvToken')
    if (!token) {
        show('请先登录哦')
        setTimeout(e => {
            location.href = './login.html'
        }, 1500)
    }
}

//请求拦截器  如果已登录  将token存入header中
axios.interceptors.request.use(config => {
    console.log(config);
    // Do something before request is sent
    if (localStorage.getItem('hmvToken')) {
        config.headers['Authorization'] = localStorage.getItem('hmvToken')
    }
    return config;
}, error => {
    // Do something with request error
    return Promise.reject(error);
})



//响应拦截器
axios.interceptors.response.use(response => {
    // Do something before response is sent
    return response.data;
}, error => {
    // Do something with response error

    console.dir(error)
    if (error.response.status === 401) {
        showToast('登录失效 请重新登录')
        localStorage.removeItem('username')
        localStorage.removeItem('hmvToken')
        setTimeout(e => {
            location.href = './login.html'
        }, 1500)
    }
    return Promise.reject(error);
})

//用户名渲染
function getUsername() {
    const username = localStorage.getItem('vusername')
    if (username) {
        document.querySelector('.username').innerHTML = username
    }
}
